package nz.ac.massey.doi_information_extractor.parser;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import org.apache.commons.lang3.StringEscapeUtils;

import nz.ac.massey.doi_information_extractor.data.Publication;


public class SCOPUSPlugin implements PluginInterface {

	private String developersID = "GKRRgFsIsIsdSgXOe3zgdC2l6ju5hd";
	private String developersSite = "http://nothing.in.particular";
	private String doi;
	private Publication result = new Publication();

	public SCOPUSPlugin(String inputdoi) {
		this.doi = inputdoi;
	}

	@Override
	public Publication call() throws Exception {
		getInformationFromDOI(doi);
		return result;
	}

	@Override
	public void getInformationFromDOI(String doi)
			throws PublicationNotFoundException, IOException {

		URL redirectPage;
		try {
				redirectPage = new URL("http://www.scopus.com/scsearchapi/search.url?devId=" + developersID + "&search=doi(" + doi + ")&callback=t");
		} catch (MalformedURLException e) {
			throw new PublicationNotFoundException(e.getMessage());
		}

		URLConnection nextPage = redirectPage.openConnection();
		nextPage.setRequestProperty("REFERER", developersSite);

		BufferedInputStream buffer = new BufferedInputStream(
				nextPage.getInputStream());

		StringBuilder builder = new StringBuilder();
		int byteRead;
		while ((byteRead = buffer.read()) != -1){
			builder.append((char) byteRead);
		}
		buffer.close();

		// Put the source together.
		String source = builder.toString();

		source = source.substring(3,source.length()-5);
		source = StringEscapeUtils.unescapeHtml4(source);

		// If there are results!
		if (source.substring(1, 3).equals("OK")) {
			String[] sourceBits = source.split(":");

			result.setArticleTitle(sourceBits[6].substring(1,sourceBits[6].length()-13));
			String pubtit = sourceBits[10].split(",")[0];
			pubtit = pubtit.substring(1,pubtit.length()-1);
			result.setPublicationTitle(pubtit);


			//Hmm.. I don't think any of the other results are actually usable.
		}
	}
	
	

}
